package main

import (
	conf "echo_prj/conf"
	h "echo_prj/handler"
	"github.com/labstack/echo"
	"github.com/labstack/echo/middleware"
	"log"
	
)

func main() {
	e := echo.New()
	e.Use(middleware.Recover())
	e.Use(middleware.GzipWithConfig(middleware.GzipConfig{
		Level: 5,
	}))
	e.Static("/", "view")


	e.POST("/api/login", handleIterceptor(h.Login, false))
	e.GET("/api/checkLogin", handleIterceptor(h.CheckLogin, true))

	e.GET("/api/getNews", handleIterceptor(h.GetNews, false))
	e.GET("/api/getNewsDetail", handleIterceptor(h.GetNewsDetail, false))
	e.GET("/api/getProduct", handleIterceptor(h.GetProduct, false))
	e.POST("/api/product", handleIterceptor(h.PostProduct, true))
	e.POST("/api/editProd", handleIterceptor(h.EditProduct, true))
	e.POST("/api/delProd", handleIterceptor(h.DelProduct, true))
	e.POST("/api/article", handleIterceptor(h.PostNews, true))
	e.POST("/api/editArticle", handleIterceptor(h.EditNews, true))
	e.POST("/api/delNews", handleIterceptor(h.DelNews, true))

	//产品、新闻图片
	e.POST("/api/fileImg", handleIterceptor(h.PostImg, true))
	//富文本图片
	e.POST("/api/textImg", handleIterceptor(h.TextImg, true))

	e.GET("/api/getBanner", handleIterceptor(h.GetBanner, false))
	e.POST("/api/banner", handleIterceptor(h.PostBanner, true))
	e.POST("/api/postBannerProd", handleIterceptor(h.PostBannerProd, true))

	e.GET("/api/getRecruit", handleIterceptor(h.GetRecruit, false))
	e.POST("/api/postRecruit", handleIterceptor(h.PostRecruit, true))
	e.POST("/api/editRecruit", handleIterceptor(h.EditRecruit, true))
	e.POST("/api/delRecruit", handleIterceptor(h.DelRecruit, true))


	//启动server时，同步一次cdn
	err := h.SyncToCdn()
	if err != nil{
		log.Println("server启动时,同步cdn失败")
	}
	//开启定时任务
	h.SetTimeOutClearImg()
	e.Logger.Fatal(e.Start(":" + conf.Conf.Port))

}

//请求拦截器
func handleIterceptor(f echo.HandlerFunc, isVerify bool) echo.HandlerFunc {
	return func(c echo.Context) error {
		log.Println(c.Request().URL)
		//请求拦截，校验token
		if isVerify {
			flag, err := h.VerifyCookie(c)
			if err != nil || !flag {
				var a = h.Res{}
				a.Code = -2
				a.Msg = "登录失效，请重新登录"
				if err != nil {
					log.Println("token检验失败")
				}
				return c.JSON(200, a)
			}
		}
		return f(c)
	}
}

